package com.dhl.demo.controller;

import com.dhl.demo.service.IRedisLockService;
import com.dhl.utils.RedisLockUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * redis分布式锁demo
 * @author danghailiang
 * @date 2023年03月12日 21:48
 */
@RestController
@RequestMapping("/demo/redis")
public class RedisLockController {
    @Resource
    private IRedisLockService redisLockService;
    @Resource
    private RedisLockUtils redisLockUtils;

    @GetMapping("/redisLockSum")
    public String redisLockSum() {
        String requestId = UUID.randomUUID().toString();
        int expire = 5;
        // 1.获取锁
        System.out.println("是否成功获取锁" + redisLockUtils.getLock(requestId, expire));
        // 启动子线程守护
        Thread lifeThread = redisLockUtils.createLifeThread(expire, requestId);
        try {
            // 线程守护
            lifeThread.setDaemon(true);
            // 启动生命线程
            lifeThread.start();
            System.out.println("是否成功获取锁" + redisLockUtils.getLock(requestId, expire));
            redisLockService.addSum();
            System.out.println("是否成功获取锁" + redisLockUtils.getLock(requestId, expire));
            redisLockService.addSum();
            System.out.println("是否成功获取锁" + redisLockUtils.getLock(requestId, expire));
            redisLockService.addSum();
            return "添加成功";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程守护
            lifeThread.interrupt();
            System.out.println(redisLockUtils.releaseLock(requestId));
        }
        return "添加失败";
    }

    @GetMapping("/sum")
    public String sum() {
        redisLockService.addSum();
        return "添加成功";
    }


}
